<template>
    <div class="city-distribution-container">
        <div class="chart-header">
            <h3 class="chart-title">河南省地级市分布</h3>
            <!-- <div class="date-navigation">
                <i class="el-icon-arrow-left date-arrow" :class="{ 'disabled': !canGoPrev }" @click="prevDate"></i>
                <span class="date-text">{{ currentDate }}</span>
                <i class="el-icon-arrow-right date-arrow" :class="{ 'disabled': !canGoNext }" @click="nextDate"></i>
            </div> -->
        </div>

        <div class="chart-content">
            <div class="map-section">
                <div ref="mapContainer" class="map-container"></div>
                <!-- <div class="map-legend">
                    <div class="legend-title">患者数</div>
                    <div class="legend-bar">
                        <div class="legend-gradient"></div>
                        <div class="legend-labels">
                            <span class="legend-min">1</span>
                            <span class="legend-max">500</span>
                        </div>
                    </div>
                </div> -->
            </div>

            <div class="table-section">
                <el-table :data="tableData" style="width: 100%" stripe @sort-change="handleSortChange">
                    <el-table-column prop="city" label="城市" min-width="120" >
                    </el-table-column>
                    <el-table-column prop="value" label="患者数" sortable="custom" min-width="120">
                        <template slot="header">
                            <span>患者数</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="proportion" label="占比" sortable="custom" min-width="100">
                    </el-table-column>
                    <template slot="empty">
                        <div class="empty-data">
                            <i class="el-icon-data-line empty-icon"></i>
                            <p class="empty-text">暂无数据</p>
                        </div>
                    </template>
                </el-table>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import '@/utils/henan'
import { getProvinceRegionDistribution } from '@/api/chenlong.js'

export default {
    name: 'CityDistribution',  //患者地域画像 - 地级分布
    props: {
        corpId: {
            type: String,
            default: ''
        },
        dateRange: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            chart: null,
            selectedCity: null,
            tableData: [],
            sorting: '',  // 排序字段
            sortType: ''  // 排序方式
        }
    },
    watch: {
        corpId: {
            handler(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.loadData()
                }
            }
        },
        dateRange: {
            handler(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.loadData()
                }
            }
        }
    },
    mounted() {
        this.initMap()
        // 初始化完成后加载数据
        this.loadData()
    },
    beforeDestroy() {
        if (this.chart) {
            this.chart.dispose()
        }
    },
    methods: {
        formatDateForApi(date) {
            // 格式化日期为API需要的格式
            const year = date.getFullYear()
            const month = date.getMonth() + 1
            const day = date.getDate()
            return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
        },
        async loadData() {
            // 根据corpId和dateRange获取数据
            try {
                const params = {
                    corpId: this.corpId.join()
                }
                
                // 使用dateRange参数
                if (this.dateRange && this.dateRange.length === 2) {
                    params.startTime = this.formatDateForApi(new Date(this.dateRange[0]))
                    params.endTime = this.formatDateForApi(new Date(this.dateRange[1]))
                } else {
                    // 如果没有dateRange，使用当前日期作为默认值
                    const today = new Date()
                    params.startTime = this.formatDateForApi(today)
                    params.endTime = this.formatDateForApi(today)
                }
                
                // 添加排序参数
                if (this.sorting && this.sortType) {
                    params.sorting = this.sorting
                    params.sortType = this.sortType
                }
                
                const res = await getProvinceRegionDistribution(params)
               // console.log(">>>", params, res);
                
                if (res.code == 200 && res.data) {
                    this.processApiData(res.data)
                } else {
                    // 处理接口返回错误的情况
                    this.tableData = []
                    this.updateMapData([])
                }
            } catch (error) {
                console.error('加载城市分布数据失败:', error)
                this.tableData = []
                this.updateMapData([])
            }
        },
        processApiData(apiData) {
            // 处理接口返回的数据，使用服务端返回的占比字段
            if (!apiData || !Array.isArray(apiData)) {
                this.tableData = []
                this.updateMapData([])
                return
            }
            
            // 处理表格数据，使用服务端返回的proportion字段
            this.tableData = apiData.map(item => ({
                city: item.name,
                value: item.value,
                proportion: item.proportion ? item.proportion + '%' : '0.00%'
            }))

            // 更新地图数据
            this.updateMapData(apiData)
        },
        updateMapData(mapData) {
            if (!this.chart) return

            // 获取当前图表配置
            const option = this.chart.getOption()
            
            // 更新地图数据
            const updatedOption = {
                ...option,
                series: [{
                    ...option.series[0],
                    data: mapData || []
                }]
            }

            // 更新visualMap的最大值
            if (mapData && mapData.length > 0) {
                const maxValue = Math.max(...mapData.map(item => item.value || 0))
                updatedOption.visualMap = {
                    ...option.visualMap,
                    max: maxValue
                }
            }

            this.chart.setOption(updatedOption)
        },
        initMap() {
            this.chart = echarts.init(this.$refs.mapContainer)

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        if (params.data) {
                            return `${params.name}<br/>患者数: ${params.data.value}人`
                        }
                        return `${params.name}<br/>患者数: 0人`
                    }
                },
                visualMap: {
                    min: 1,
                    max: 500,
                    left: 'left',
                    top: 'bottom',
                    text: ['高', '低'],
                    calculable: true,
                    inRange: {
                        color: ['#e6f7ff', '#52c41a']
                    },
                    show: false
                },
                geo: {
                    map: '河南',
                    roam: false,
                    scaleLimit: {
                        min: 1,
                        max: 2
                    },
                    zoom: 1.2,
                    top: 50,
                    left: 50,
                    right: 50,
                    bottom: 50,
                    itemStyle: {
                        normal: {
                            areaColor: '#f0f0f0',
                            borderColor: '#999',
                            borderWidth: 1
                        },
                        emphasis: {
                            areaColor: '#74b9ff',
                            borderColor: '#0984e3',
                            borderWidth: 3,
                            shadowColor: 'rgba(116, 185, 255, 0.5)',
                            shadowBlur: 10
                        }
                    },
                    label: {
                        normal: {
                            show: true,
                            fontSize: 14,
                            color: '#000000',
                            fontWeight: 'bold',
                            textShadowColor: '#ffffff',
                            textShadowBlur: 2,
                            textShadowOffsetX: 1,
                            textShadowOffsetY: 1
                        },
                        emphasis: {
                            show: true,
                            fontSize: 16,
                            color: '#000000',
                            fontWeight: 'bold',
                            textShadowColor: '#ffffff',
                            textShadowBlur: 3,
                            textShadowOffsetX: 1,
                            textShadowOffsetY: 1
                        }
                    }
                },
                series: [
                    {
                        name: '患者数',
                        type: 'map',
                        map: '河南',
                        geoIndex: 0,
                        itemStyle: {
                            normal: {
                                areaColor: '#f0f0f0',
                                borderColor: '#999',
                                borderWidth: 1
                            },
                            emphasis: {
                                areaColor: '#74b9ff',
                                borderColor: '#0984e3',
                                borderWidth: 3,
                                shadowColor: 'rgba(116, 185, 255, 0.5)',
                                shadowBlur: 10
                            }
                        },
                        data: []
                    }
                ]
            }

            this.chart.setOption(option)

            // 添加点击事件
            this.chart.on('click', this.handleMapClick)

            // 响应式处理
            window.addEventListener('resize', this.handleResize)
        },

        handleResize() {
            if (this.chart) {
                this.chart.resize()
            }
        },

        // 表格排序处理
        async handleSortChange({ column, prop, order }) {
            if (order === null) {
                // 取消排序
                this.sorting = ''
                this.sortType = ''
            } else {
                // 设置排序字段和排序方式
                // 对于proportion字段，API可能期望的是proportionValue或其他字段名
                const sortFieldMap = {
                    'value': 'value',           // 患者数字段
                    'proportion': 'proportion'  // 占比字段，如果API期望其他名称，请修改这里
                }
                
                this.sorting = sortFieldMap[prop] || prop
                this.sortType = order === 'ascending' ? 'asc' : 'desc'
            }

            // 重新加载数据
            try {
                await this.loadData()
                this.$message.success('排序成功')
            } catch (error) {
                this.$message.error('排序失败，请重试')
            }
        },



        handleMapClick(params) {
            if (params.componentType === 'series') {
                this.selectedCity = params.name
                this.updateMapSelection()
            }
        },

        updateMapSelection() {
            if (!this.chart) return

            const option = this.chart.getOption()
            const seriesData = option.series[0].data

            // 更新数据，为选中的城市添加特殊标记
            const updatedData = seriesData.map(item => {
                if (item.name === this.selectedCity) {
                    return {
                        ...item,
                        itemStyle: {
                            areaColor: '#2d3436',
                            borderColor: '#0984e3',
                            borderWidth: 3,
                            shadowColor: 'rgba(9, 132, 227, 0.6)',
                            shadowBlur: 15
                        }
                    }
                }
                return item
            })

            this.chart.setOption({
                series: [{
                    data: updatedData
                }]
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.city-distribution-container {
    background: #ffffff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    height: 100%;
}

.chart-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    position: relative;
}

.chart-title {
    font-size: 18px;
    font-weight: 600;
    color: #333333;
    margin: 0;
}

.date-navigation {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: #666666;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

.date-arrow {
    cursor: pointer;
    font-size: 16px;
    color: #999999;
    transition: color 0.3s;

    &:hover {
        color: #409eff;
    }
    
    &.disabled {
        color: #c0c4cc;
        cursor: not-allowed;
        
        &:hover {
            color: #c0c4cc;
        }
    }
}

.date-text {
    font-size: 14px;
    color: #666666;
    min-width: 120px;
    text-align: center;
}

.chart-content {
    display: flex;
    // justify-content: flex-end;
    gap: 20px;
    height: calc(100% - 60px);
}

.map-section {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.map-container {
    flex: 1;
    min-height: 400px;
}

.map-legend {
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 10px;
}

.legend-title {
    font-size: 12px;
    color: #666666;
}

.legend-bar {
    position: relative;
    width: 100px;
    height: 20px;
}

.legend-gradient {
    width: 100%;
    height: 100%;
    background: linear-gradient(to right, #e6f7ff, #52c41a);
    border-radius: 2px;
}

.legend-labels {
    position: absolute;
    top: -20px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    font-size: 10px;
    color: #666666;
}

.table-section {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.sort-icon {
    color: #52c41a;
    margin-left: 4px;
}

.sort-number {
    display: inline-block;
    width: 16px;
    height: 16px;
    background-color: #52c41a;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 16px;
    font-size: 10px;
    margin-left: 4px;
}


.empty-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    color: #999999;
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    color: #c0c4cc;
}

.empty-text {
    margin: 0;
    font-size: 14px;
    color: #999999;
}

// 响应式设计
@media (max-width: 1200px) {
    .chart-content {
        flex-direction: column;
        gap: 16px;
    }

    .map-container {
        min-height: 300px;
    }
}

@media (max-width: 768px) {
    .chart-header {
        flex-direction: column;
        gap: 12px;
    }

    .date-navigation {
        position: static;
        transform: none;
    }
}
</style>
